import axios from 'axios'
import { ElMessage } from 'element-plus'

let AUTH_TOKEN = ''
export function updateAuthToken(token: string) {
  AUTH_TOKEN = token || ''
}

const http = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '',
  timeout: 15000,
  headers: { 'Content-Type': 'application/json' },
})

http.interceptors.request.use((config) => {
  if (AUTH_TOKEN) {
    config.headers = config.headers || {}
    ;(config.headers as Record<string, string>)['Authorization'] = `Bearer ${AUTH_TOKEN}`
  }
  return config
})

http.interceptors.response.use(
  (res) => res,
  (err) => {
    const msg = err?.response?.data?.message || err.message || '요청 실패'
    ElMessage.error(msg)
    return Promise.reject(err)
  }
)

export default http

